﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Antlr.StringTemplate;
using TuKu.Common;
using System.IO;
using TuKu.BLL;
using TuKu.Load;
using System.Resources;
using System.Reflection;

namespace TuKu
{
    public partial class TemplateMain : Form
    {
        DataTable dt;
        public TemplateMain()
        {
            InitializeComponent();
        }
        #region 基本操作
        /// <summary>
        /// 生成首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateIndex_Click(object sender, EventArgs e)
        {
            cateSugstDataSourceCreate();

            StringTemplate index = TemplateClass.initTemplate("index");
            StringTemplate groupList = TemplateClass.initTemplate("groupList");
            DataTable group = new BLL.Group().GetList(" addtime>#2000/01/01# order by OrderID").Tables[0];
            DataTable subgroup = new DataTable();
            foreach (DataRow dr_group in group.Rows)
            {
                subgroup = new BLL.subGroup().GetList(" groupid =" + dr_group["id"].ToString() + " order by OrderID").Tables[0];
                foreach (DataRow dr_subgroup in subgroup.Rows)
                {
                    groupList.SetAttribute("subGroup", "<li><a href='" + dr_group["Pin"].ToString() + "/" + dr_subgroup["Pin"].ToString() + "/list.htm'>" + dr_subgroup["title"].ToString() + "</a></li>");
                }
                groupList.SetAttribute("Group", "<a href='" + dr_group["Pin"].ToString() + "/list.htm" + "'>" + dr_group["title"].ToString() + "</a>");
                index.SetAttribute("groupList", groupList.ToString());
                groupList.RemoveAttribute("Group");
                groupList.RemoveAttribute("subGroup");
            }


            if (!Directory.Exists(Common.PathClass.webpath))
            {
                FileManager.CreateFoler(Common.PathClass.webpath);
            }
            FileManager.WriteFile(Common.PathClass.webpath + "\\index.htm", index.ToString(), false);
            MessageBox.Show("首页生成完毕!");
        }

        private void cateSugstDataSourceCreate()
        {
            DataTable dt = new BLL.Group().GetAllList().Tables[0];
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append("<li>\r\n");
                sb.Append("<a href='" + dr["Pin"].ToString() + "/list.htm" + "'>" + dr["Title"].ToString() + "</a>\r\n");
                sb.Append("</li>\r\n");
            }
            FileManager.WriteFile(@"d:\tuku\template\cateSugstDataSource.st", sb.ToString(), false);
        }
        /// <summary>
        /// 生成一级目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFolderCreate_Click(object sender, EventArgs e)
        {
            DataTable dt = new BLL.Group().GetList(" 1=1 order by id desc ").Tables[0];
            DataTable sub = new DataTable();
            StringTemplate list = TemplateClass.initTemplate("list");
            StringBuilder li = new StringBuilder();
            LoadingHandler.Show(this, args =>
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        Common.PathClass.initGroupPath(dr["title"].ToString());
                        sub = new BLL.subGroup().GetList(" groupid=" + dr["id"].ToString()).Tables[0];
                        foreach (DataRow dr_sub in sub.Rows)
                        {
                            li.Append("<li><a href='/");
                            li.Append(dr["title"].ToString().toQuanPin() + "/");
                            li.Append(dr_sub["title"].ToString().toQuanPin());
                            li.Append("/list.htm' title='" + dr_sub["title"].ToString() + "' >");
                            li.Append(dr_sub["title"].ToString() + "</a></li>");
                            list.SetAttribute("subGroupList", li.ToString());
                            li.Remove(0, li.Length);
                            li.Append("<div ><a href='" + dr_sub["title"].ToString().toQuanPin() + "/" + dr_sub["title"].ToString().toQuanPin() + "_" + new BLL.Topic().getMinTopicID(int.Parse(dr_sub["id"].ToString())).ToString() + ".htm' target='_blank'>\r\n");
                            li.Append("<img src='" + dr_sub["title"].ToString().toQuanPin() + "/logo.jpg'  alt='" + dr_sub["title"].ToString() + "' />");
                            li.Append("<span>" + dr_sub["title"].ToString() + "</span></a></div>\r\n");
                            list.SetAttribute("listlogo", li.ToString());
                            li.Remove(0, li.Length);
                        }
                        list.SetAttribute("group", dr["title"].ToString());
                        FileManager.WriteFile(Common.PathClass.webpath + "\\" + dr["Pin"].ToString() + "\\list.htm", list.ToString(), false);
                        list.RemoveAttribute("group");
                        list.RemoveAttribute("subGroupList");
                        list.RemoveAttribute("listlogo");

                    }
                });
            MessageBox.Show("一级目录生成完毕!");

        }
        /// <summary>
        /// 生成二级目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            List<Model.subGroup> list = new BLL.subGroup().GetModelList(" 1=1 ");
            string folderName = string.Empty;
            LoadingHandler.Show(this, args =>
            {
                foreach (Model.subGroup model in list)
                {
                    //初始化目录
                    Common.PathClass.initSubGroupPath(new BLL.Group().GetModel(model.GroupID).Title, model.Title.Trim());
                }
            });
            MessageBox.Show("二级目录生成完毕!");
        }
        #endregion

        private void TemplateMain_Load(object sender, EventArgs e)
        {
            DataBindClass.GroupBind(combGroup);
        }

        private void combGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            int groupid = int.Parse(new BLL.Group().GetModel(combGroup.Text).ID.ToString());
            DataBindClass.subGroupBind(groupid, listsubGroup);
        }

        #region 页面操作

        private void listsubGroup_DoubleClick(object sender, EventArgs e)
        {
            //MessageBox.Show(listsubGroup.SelectedItem.ToString());
            int subGroupid = int.Parse(new BLL.subGroup().GetModel(listsubGroup.SelectedItem.ToString()).ID.ToString());
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {

                }
            }

        }

        private void listsubGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listsubGroup.SelectedItems.Count > 0)
            {
                int subGroupid = int.Parse(new BLL.subGroup().GetModel(listsubGroup.SelectedItems[0].ToString()).ID.ToString());
                dt = new BLL.Topic().GetList(" subGroupid=" + subGroupid).Tables[0];
                lblCount.Text = "该分类下：（" + dt.Rows.Count.ToString() + "）条记录";
            }
        }


        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(FileManager.CreateDateTimePath());
        }



        private void btnCreateSingle_Click(object sender, EventArgs e)
        {
            if (listsubGroup.SelectedItems.Count > 0)
            {
                foreach (string subGroupName in listsubGroup.SelectedItems)
                {
                    if (subGroupName.IsNotNullOrEmpty())
                    {
                        int Groupid = int.Parse(new BLL.subGroup().GetModel(subGroupName).GroupID.ToString());//父类ID
                        string GroupName = new BLL.Group().GetModel(Groupid).Title;//父类名
                        string subGroupPy = Common.Hz2Py.Convert(subGroupName);//子类拼音
                        int subGroupid = int.Parse(new BLL.subGroup().GetModel(subGroupName).ID.ToString());//子类ID
                        PathClass.initSubGroupPath(GroupName, subGroupName);//初始化路径
                        string subGroupPath = PathClass.webpath + "\\" + GroupName.toQuanPin() + "\\" + subGroupPy;//子类路径
                        string imgFileName = string.Empty;
                        DataTable dt = new BLL.Topic().GetList(" subGroupid = " + subGroupid.ToString() + " order by id").Tables[0];
                        StringTemplate st = TemplateClass.initTemplate("view");///初始化展示页模板
                        LoadingHandler.Show(this, args =>
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                imgFileName = subGroupPy + "_" + dt.Rows[i]["ID"].ToString() + "." + dt.Rows[i]["body"].ToString().getFileExtends();
                                if (!Directory.Exists(subGroupPath + "\\images\\" + dt.Rows[i]["AddTime"].ToString().toDateString()))
                                {
                                    Directory.CreateDirectory(subGroupPath + "\\images\\" + dt.Rows[i]["AddTime"].ToString().toDateString());
                                }
                                File.Copy(dt.Rows[i]["body"].ToString(), subGroupPath + "\\images\\" + dt.Rows[i]["AddTime"].ToString().toDateString() + "\\" + imgFileName, true);

                                st.SetAttribute("subgroup", subGroupName);
                                st.SetAttribute("imgFileName", dt.Rows[i]["AddTime"].ToString().toDateString() + "/" + imgFileName);
                                st.SetAttribute("siteName", System.Configuration.ConfigurationManager.AppSettings["siteName"]);
                                st.SetAttribute("GroupName", GroupName);
                                st.SetAttribute("GroupPy", GroupName.toQuanPin());
                                st.SetAttribute("siteUrl", System.Configuration.ConfigurationManager.AppSettings["siteUrl"]);
                                st.SetAttribute("beian", System.Configuration.ConfigurationManager.AppSettings["beian"]);
                                st.SetAttribute("jscode", System.Configuration.ConfigurationManager.AppSettings["jscode"]);

                               
                                //第一页的上一页返回列表页
                                if (i == 0)
                                {
                                    st.SetAttribute("PreviewPage", "../list.htm");
                                }
                                else
                                {
                                    st.SetAttribute("PreviewPage", subGroupPy + "_" + dt.Rows[i - 1]["ID"].ToString() + ".htm");
                                }
                                //最后一面的下一页返回列表页
                                if (i == dt.Rows.Count - 1)
                                    st.SetAttribute("NextPage", "../list.htm");
                                else
                                    st.SetAttribute("NextPage", subGroupPy + "_" + dt.Rows[i + 1]["ID"].ToString() + ".htm");
                                if (i == 0)
                                FileManager.WriteFile(Common.PathClass.webpath + "\\" + GroupName.toQuanPin() + "\\" + subGroupPy + "\\list.htm", st.ToString(), false);
                                FileManager.WriteFile(Common.PathClass.webpath + "\\" + GroupName.toQuanPin() + "\\" + subGroupPy + "\\" + subGroupPy + "_" + dt.Rows[i]["ID"].ToString() + ".htm", st.ToString(), false);

                                st.RemoveAttribute("subgroup");
                                st.RemoveAttribute("imgFileName");
                                st.RemoveAttribute("PreviewPage");
                                st.RemoveAttribute("NextPage");


                                st.RemoveAttribute("subgroup");
                                st.RemoveAttribute("siteName");
                                st.RemoveAttribute("GroupName");
                                st.RemoveAttribute("GroupPy");
                                st.RemoveAttribute("siteUrl");
                                st.RemoveAttribute("beian");
                                st.RemoveAttribute("jscode");


                            }
                        });

                    }
                    else
                    {
                        MessageBox.Show("请选择子类");
                    }
                }
            }

        }



    }
}
